package controllers

import (
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"github.com/astaxie/beego/utils/pagination"
	"math/rand"
	"smallgift/models"
	"strconv"
	"time"
)

type ActivityController struct {
	Router
}

// @router /list [post]
func (this *ActivityController) List() {
	page, _ := this.GetInt("page", 1)
	rows, _ := this.GetInt("rows", 10)

	sql := fmt.Sprintf(" SELECT  id, activity_name, activity_amount, status, top_rule, tail_rule, middle_num, created FROM `activity` ") + fmt.Sprintf(" ORDER BY created DESC LIMIT  %d,%d ", (page-1)*rows, rows)
	count_sql := fmt.Sprintf(" SELECT  count(*) as total_num FROM `activity` ")

	beego.Debug(sql)
	beego.Debug(count_sql)

	total_num := TotalNum{}
	o := orm.NewOrm()
	if err := o.Raw(count_sql).QueryRow(&total_num); err != nil && err != orm.ErrNoRows {
		this.Data["json"] = BaseBean{"-1", "统计sql报错:" + err.Error()}
		this.ServeJSON()
		return
	} else if err == orm.ErrNoRows {

		p := pagination.NewPaginator(this.Ctx.Request, rows, 0)
		data_list := []Activitybean{}
		resp_data := ActivitysBean{}
		resp_data.Code = "0"
		resp_data.Msg = "SUCCESS"
		resp_data.TotalNum = 0
		resp_data.TotalPage = p.PageNums()
		resp_data.Page = page
		resp_data.Rows = rows
		resp_data.List = data_list

		this.Data["json"] = resp_data
		this.ServeJSON()
		return

	} else {

		int_total_num, _ := strconv.Atoi(total_num.TotalNum)
		p := pagination.NewPaginator(this.Ctx.Request, rows, int_total_num)

		data_list := []Activitybean{}

		if _, err := o.Raw(sql).QueryRows(&data_list); err != nil {
			this.Data["json"] = this.GenErrResp("sql报错:" + err.Error())
			this.ServeJSON()
			return
		}
		beego.Debug(data_list)

		resp_data := ActivitysBean{}
		resp_data.Code = "0"
		resp_data.Msg = "SUCCESS"
		resp_data.TotalNum = int_total_num
		resp_data.TotalPage = p.PageNums()
		resp_data.Page = page
		resp_data.Rows = rows
		resp_data.List = data_list

		this.Data["json"] = resp_data
		this.ServeJSON()
		return
	}

}

// @router /create [post]
func (this *ActivityController) Create() {

	activityName := this.GetStr("activity_name", "")
	activityAmount := this.GetStr("activity_amount", "")

	if len(activityName) == 0 || len(activityAmount) == 0 {
		this.Data["json"] = this.GenErrResp("参数错误")
		this.ServeJSON()
		return
	}

	activity := models.Activity{}
	activity.ActivityName = activityName
	if err := activity.Read("ActivityName"); err == nil {
		this.Data["json"] = this.GenErrResp("活动名已存在")
		this.ServeJSON()
		return
	}

	activity.Created = time.Now().Format("2006-01-02 15:04:05")
	activity.ActivityAmount = activityAmount
	activity.Status = "N"
	activity.Insert()

	base_bean := BaseBean{}
	base_bean.Code = "0"
	base_bean.Message = "创建成功"
	this.Data["json"] = base_bean
	this.ServeJSON()
	return
}

// @router /edit [post]
func (this *ActivityController) Edit() {
	id, _ := this.GetInt("activity_id", 0)
	activityName := this.GetStr("activity_name", "")
	activityAmount := this.GetStr("activity_amount", "")

	if id == 0 {
		this.Data["json"] = this.GenErrResp("参数错误")
		this.ServeJSON()
		return
	}

	activity := models.Activity{}
	activity.Id = id
	if err := activity.Read("Id"); err != nil {
		this.Data["json"] = this.GenErrResp("活动不存在")
		this.ServeJSON()
		return
	}

	if len(activityName) != 0 {
		activity.ActivityName = activityName
	}

	if len(activityAmount) != 0 {
		activity.ActivityAmount = activityAmount
	}

	if err := activity.Update(); err != nil {
		this.Data["json"] = this.GenErrResp("更新失败")
		this.ServeJSON()
		return
	}

	base_bean := BaseBean{}
	base_bean.Code = "0"
	base_bean.Message = "编辑成功"
	this.Data["json"] = base_bean
	this.ServeJSON()
	return
}

// @router /createvoucher [post]
func (this *ActivityController) CreateVoucher() {
	activityId, _ := this.GetInt("activity_id", 0)
	num, _ := this.GetInt("num", 0)
	topRule := this.GetStr("top_rule", "")
	tailRule := this.GetStr("tail_rule", "")
	middleNum, _ := this.GetInt("middle_num", 6)

	if activityId == 0 || num == 0 {
		this.Data["json"] = this.GenErrResp("参数错误")
		this.ServeJSON()
		return
	}

	activity := models.Activity{}
	activity.Id = activityId
	if err := activity.Read("Id"); err != nil {
		this.Data["json"] = this.GenErrResp(err.Error())
		this.ServeJSON()
		return
	}


	if activity.Status == "N" || len(activity.Status) == 0{
		//未创建过规则
		if len(topRule) == 0 || len(tailRule) == 0 || middleNum == 0 {
			this.Data["json"] = this.GenErrResp("参数错误")
			this.ServeJSON()
			return
		}
		activity.TailRule = tailRule
		activity.TopRule = topRule
		activity.MiddleNum = middleNum
		activity.Status = "Y"
		if err := activity.Update("TailRule", "TopRule", "MiddleNum", "Status"); err != nil {
			this.Data["json"] = this.GenErrResp(err.Error())
			this.ServeJSON()
			return
		}

		beego.Debug("开始生成券")
		createV(num, topRule, tailRule, activityId, middleNum)
		this.Data["json"] = this.GenSucResp("发券成功")
		this.ServeJSON()
		return
	}else if activity.Status == "Y"{
		beego.Debug("开始生成券")
		createV(num, activity.TopRule, activity.TailRule, activityId, activity.MiddleNum)
		this.Data["json"] = this.GenSucResp("发券成功")
		this.ServeJSON()
		return
	}else{
		this.Data["json"] = this.GenErrResp("参数错误")
		this.ServeJSON()
		return

	}

}


func createV(num int, topRule string, tailRule string, activityId int, middleNum int){
	var i = num
	for {
		if i == 0 {
			break
		}
		order := models.Order{}
		ticketNo := topRule + GetRandomNumberString(middleNum) + tailRule
		order.TicketNo = ticketNo
		if err := order.Read("TicketNo"); err != nil && err == orm.ErrNoRows {
			order.TicketPwd = GetRandomLetterString(6)
			order.ActivityId = activityId
			order.Insert()
			i--
		}
	}
}

func GetRandomNumberString(l int) string {
	str := "0123456789"
	bytes := []byte(str)
	result := []byte{}
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	for i := 0; i < l; i++ {
		result = append(result, bytes[r.Intn(len(bytes))])
	}
	return string(result)
}

func GetRandomLetterString(l int) string {
	str := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
	bytes := []byte(str)
	result := []byte{}
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	for i := 0; i < l; i++ {
		result = append(result, bytes[r.Intn(len(bytes))])
	}
	return string(result)
}
